# -*- coding:utf-8 -*-

import requests
from lxml import etree
from fake_useragent import UserAgent
from http import cookiejar
import json
from datetime import datetime
import time
import re
import csv
from pymongo import MongoClient


requests.packages.urllib3.disable_warnings()  # 忽略HTTPS安全警告


"""
微信安全员
"""

class Test_Get():
    def __init__(self):
        #声明一个CookieJar对象实例来保存cookie
        # requests.utils.dict_from_cookiejar(html.cookies)  # 获取cookies转dict
        self.cookie = cookiejar.CookieJar()
        # ua = UserAgent(use_cache_server=False)  # 禁用服务器缓存
        self.headers = {
            # 'User-Agent': ua.random,
            'Host': 'wx.adodl.com',
            'Connection': 'keep-alive',
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Origin': 'https://wx.adodl.com',
            'X-Requested-With': 'XMLHttpRequest',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36 QBCore/4.0.1301.400 QQBrowser/9.0.2524.400 Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2875.116 Safari/537.36 NetType/WIFI MicroMessenger/7.0.5 WindowsWechat',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Referer': 'https://wx.adodl.com/app/run/Exam',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.5;q=0.4',
            'Cookie': 'ASP.NET_SessionId=qx5kk3aafc1thjphch0lpbra; .ASPXAUTH=529F825176756B07605BBEDC3DF8BF54A6FBF923F50E0CA9F7C089B0DD1A7206E7F27380B10371C931EA8974D83E86089EA6F51D2085F31C93416FB436D31BC0C8C69B00842E2470D43CDE77185D00A375C38D2DA1A03053425688F2C5AC13399BCC49846F55A7F74B094633E7B13F2EDAFD1217E31BAB9780F51FEA52555250186845B71BA40C496751BD11400E3DC1C881DE37C16BCF7D9500136B6AF817D1DCED277B97989652621CA2658A915119C51AC74D085C09A6948BFC16D3615D083C1FA920CBFDEACC4B8CCC21862699F7792AAB15611BB87B3B4C03C6C2CA957E2AFC0F6FA21B7F4A08D46602D5779526BDD2198AC3B44ED48523B5B87BFC420D6812ABCE68F6F4F3AB37132EC021AB0C3EECE40A6734D14F7C0AEB9115848D0833ED56A68C174524760F5D484D12B6E73178B934B892B057F1E50D914947FCCC3D1FE5D014394D03422A70412AFE3FBEEC416FF47B60B15B715A194373DFD419A03D4A23ACC35976E535B300749D9B8E911E5E6BF347B064D575FD8BE87FD4A6F6AE81DA4FB4B7CAD78E802E136F7731D9CF10E26FBE6B7AB668A7B5904EE254F860C37EAB6D3046B305BB78D2E9DBA93EC3E36173F6019A5DAA4A36591C98A0E4E3B4CA8167028C125950BF3FA7ADA48E38D72CF2FF5DF26C945AEB619B9A76EF377E839DA474AA1ED348E8918D53BB5FBAA152DC6DEDA37EE9ABA0E17BC992A81CEB6433C186AA8DE23551004AF9BDD442D8E7DFF5B0B438A46CC589F9C707CF785ED7718F38523BFDDE86250FB633537296A84029B4F471DDC089C834155068A4BCDC8C98BE508FABE56E461A8F41533F60CA1C22C60F1D83AEA2AEC59424FDF763F13416898B3A2BF8E280E73C60A0751246C8D0B948218020F3D19101A9834D38A7DCCC61EE57E38368677552EBB5F6913DB5A13CADE65C5A3618DD56FFFA776AF99D329C6DBFE54A93B4DCCD15EAD59455640481764156E2B4710E3109F8DC2BE7893280350C6DC9BDD51E3F672DC9076FD3A0B678B2309F77749542EA99D3600CAABBD786E4BF68DBBD05B84F77F49323508BC0C1E52FDA771B7770B1365C6E9BDDD11D87EDBF54185DE6B75F77CF9DBF61DE80CC5645467D2B65F0FD; Passport=%7b%22ID%22%3a630762%2c%22Guid%22%3a%2250e64ecdca0b453b919f0e52d1e96ad6%22%2c%22UserName%22%3a%22%e5%bc%a0%e4%b8%89%22%2c%22UserLogo%22%3a%22http%3a%2f%2fthirdwx.qlogo.cn%2fmmopen%2fvi_32%2f55PgTOFO6vfHia5rV2prHRbOHDCIFibFEb98dLQOhicUic6LCibka1twJNbQqRhtuWX8snJq4S8IuibYic0usuWWz3Ijg%2f132%22%2c%22CellPhone%22%3a%22%22%2c%22Email%22%3a%22%22%2c%22Role%22%3a%22User%22%2c%22AgentID%22%3a0%2c%22Password%22%3a%22%22%7d'



        }
    def get_ry(self):
        postData1 = {
            'ParentGuid': 'b6037e8222da43cdbfe44ba0abde84cf',
        }
        url = "https://wx.adodl.com/Api/QueryList/TreeChildNodes"
        html1 = HttpUtils.do_request("POST", url, self.headers, postData1)
        data_json1 = json.loads(html1.text)
        for d1 in data_json1['data']:
            id1 = d1['ID']
            Guid1 = d1['Guid']
            Name1 = d1['Name']
            Title1 = d1['Title']
            postData2 = {
                'ParentGuid': Guid1,
            }
            html2 = HttpUtils.do_request("POST", url, self.headers, postData2)
            data_json2 = json.loads(html2.text)
            for d2 in data_json2['data']:
                id2 = d2['ID']
                Guid2 = d2['Guid']
                Name2 = d2['Name']
                Title2 = d2['Title']
                postData3 = {
                    'ParentGuid': Guid2,
                }
                html3 = HttpUtils.do_request("POST", url, self.headers, postData3)
                data_json3 = json.loads(html3.text)
                for d3 in data_json3['data']:
                    id3 = d3['ID']
                    Guid3 = d3['Guid']
                    Name3 = d3['Name']
                    Title3 = d3['Title']
                    file_name = Title1 + "_" + Title2 + "_" + Title3
                    print("==========================")
                    print(file_name)
                    self.get_contents(file_name, id3)



    def get_contents(self, file_name, id):
        postData4 = {
            'ClassID': '345',# 393中
            'Area': '',
            'Status': '32',
        }
        # 写csv
        with open("./" + file_name + ".csv", "a+", encoding="utf-8-sig", newline="") as f:
            csv_writer = csv.writer(f)
            csv_writer.writerow(['题目序号', '题目内容', '1、单选 2、多选  0、判断', '题目选项（使用~!!~隔开）', '答案', '解析'])
        for i in range(1, 10):
            # url4 = f"https://wx.adodl.com/Api/QueryPage/QuestionData?ps=200&order=ID&sort=asc&p={i}"
            url4 = f"https://wx.adodl.com/Api/QueryPage/FilterQuestionData?ps=200&order=ID&sort=asc&p={i}"
            url4 = f"https://wx.adodl.com/Api/QueryPage/FilterQuestionData?ps=200&order=ID&sort=asc&p=6"
            html4 = HttpUtils.do_request("POST", url4, self.headers, postData4)
            data_json4 = json.loads(html4.text)
            for d4 in data_json4['data']['DataList']:
                dict_data = dict()
                ID = d4['ID']
                Answer = d4['Answer']
                Question = d4['Question']
                if d4['QType'] == 0:  # 单选
                    q_type = "1"
                    Choice = d4['Choice'].replace(",", "~!!~").replace("[", "").replace("]", "").replace("\"", "")
                elif d4['QType'] == 1:  # 多选
                    q_type = "2"
                    Choice = d4['Choice'].replace(",", "~!!~").replace("[", "").replace("]", "").replace("\"", "")
                elif d4['QType'] == 2:  # 判断
                    q_type = "0"
                    Choice = ""
                else:
                    q_type = "66"

                # 写csv
                with open("./" + file_name + ".csv", "a+", encoding="utf-8-sig", newline="") as f:
                    csv_writer = csv.writer(f)
                    csv_writer.writerow([ID, Question, q_type, Choice, Answer])


if __name__ == '__main__':
    test_get = Test_Get()
    # test_get.get_ry()
    # for i in range(1, 11):
    #     print(f"============第【{i}】页=============")
    #     test_get.get_contents(i)
    test_get.get_contents("高级", 393)
